<script lang="ts" setup>
import { getPatientConsultOrderAPI } from '@/api/Department'
import { getPatientConsultOrderPreAPI, postPatientConsultPayApi } from '@/api/OrderPre'
import { addPatientAPI, getPatientInfoByIdAPI } from '@/api/patient'
import { useConsultStore } from '@/store/Consult'
import type { GetPatientConsultOrderPreData } from '@/types/OrderPre'
import type { GetPatientMylistItem } from '@/types/patient'
import { onMounted, ref } from 'vue'
import customPayment from '@/components/custom-payment/customPayment.vue'

// 是否同意支付协议
const isAgree = ref(false)

const store = useConsultStore()
const OrderPreInfo = ref<GetPatientConsultOrderPreData>()
const getOrderPre = async () => {
  const res = await getPatientConsultOrderPreAPI({
    type: store.type,
    illnessType: store.illnessType,
  })
  // console.log(res);
  OrderPreInfo.value = res.data
}
getOrderPre()

const patientInfo = ref<GetPatientMylistItem>()
// 查询患者信息
const getPatientInfo = async () => {
  const res = await getPatientInfoByIdAPI(store.patientId)
  patientInfo.value = res.data
}
getPatientInfo()

const orderId = ref('')
const customPaymentRef = ref<UniHelper.UniPopupInstance>()
// 立即支付
const handlePay = async () => {
  // 如果订单id存在, 则不进行提交
  if (orderId.value) {
    return uni.showToast({ title: '订单已提交, 请勿重复提交', icon: 'none' })
  }
  const res = await getPatientConsultOrderAPI({
    type: Number(store.type), // 就诊类型
    illnessType: Number(store.illnessType), // 病情类型
    patientId: store.patientId, // 患者id
    depId: store.depId, // 科室id
    illnessDesc: store.illnessInfo.illnessDesc, // 病情描述
    illnessTime: store.illnessInfo.illnessTime, // 病情时间
    consultFlag: store.illnessInfo.consultFlag, // 咨询标志
    pictures: store.illnessInfo.pictures, // 图片
  })
  console.log(res)
  // 接受Id
  orderId.value = res.data.id
  // 将pinia中缓存的数据清空掉, 避免重复提交
  // store.reset()
  // 打开支付弹窗
  customPaymentRef.value?.open?.()
}

const emit = defineEmits<{
  close: [] // 关闭支付弹窗
  confirm: [index: number] // 确认支付
  change: [index: number] // 支付方式改变
}>()

const handleClose = async () => {
  // 二次确认提示
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  // 如果用户选择关闭,则关闭支付弹窗
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}

// 确认支付
const handleConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({
      title: '微信支付暂不支持,请使用支付宝支付',
      icon: 'none',
    })
    /* #ifdef MP-WEIXIN */
    /* #endif */
  } else if (index === 1) {
    /* #ifndef MP-WEIXIN */
    const res = await postPatientConsultPayApi({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    // console.log(res);
    location.href = res.data.payUrl
    /* #endif */
  }
}

// 支付方式改变
const handleChange = (index: number) => {
  console.log('切换支付方式', index)
}
</script>

<template>
  <scroll-view>
    <view class="payment-page" :data="OrderPreInfo">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${OrderPreInfo?.payment ?? 0}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-￥${OrderPreInfo?.couponDeduction ?? 0}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ OrderPreInfo?.pointDeduction ?? 0 }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ OrderPreInfo?.actualPayment ?? 0 }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false" :data="patientInfo">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientInfo?.name }} | {{ patientInfo?.genderValue }} | {{ patientInfo?.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <view class="payment-agreement">
        <radio color="#20c6b2" @click="isAgree = !isAgree" :checked="isAgree" />我已同意<text
          style="color: #20c6b2"
          >支付协议</text
        >
      </view>
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ OrderPreInfo?.actualPayment }}</text>
      </view>
      <button class="uni-button" @click="handlePay" :disabled="!isAgree">立即支付</button>
    </view>
    <customPayment
      ref="customPaymentRef"
      :order-id="orderId"
      :amount="OrderPreInfo?.actualPayment ?? 0"
      @close="handleClose"
      @confirm="handleConfirm"
      @change="handleChange"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
